<template>
  <div>
    <van-nav-bar title="黑马头条-登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="mobile"
        label="手机号码"
        required
        placeholder="请输入手机号码"
        :rules="[
          { required: true, message: '请填写用户名' },
          { pattern: /^1[3456789]\d{9}$/, message: '请填写正确手机号' }
        ]"
      />
      <van-field
        v-model="password"
        required
        type="password"
        name="code"
        label="验证码"
        placeholder="请输入密码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '请填写正确验证码' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" :disabled="isLoading" :loading="isLoading"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { MY } from '@/utile/Notifiy.js'
import { setLoginAPI } from '@/api/login.js'
export default {
  name: 'Login',
  data() {
    return {
      username: '13313354284', // 第一个输入框双向绑定
      password: '246810', // 第二个输入框双向绑定
      isLoading: false // 禁用按钮
    }
  },
  methods: {
    ...mapMutations(['setToken', 'setRefresh_Token']),
    async onSubmit(values) {
      this.isLoading = true
      try {
        const res = await setLoginAPI(values)
        const { token, refresh_token } = res.data.data
        this.setToken(token)
        this.setRefresh_Token(refresh_token)
        console.log(res)

        MY({ type: 'success', message: '登录成功' })
        const hisPath = this.$route.query.path
        console.log(hisPath)
        this.$router.replace({
          path: hisPath || '/layout'
        })
      } catch (e) {
        console.error(e)
        MY({ type: 'warning', message: '手机号或密码错误' })
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style lang="less" scoped></style>
